<template>
  <div v-loading="load">
    <div
      slot="footer"
      class="dialog-footer"
      v-loading.fullscreen.lock="fullscreenLoading"
    />
    <el-form
      :inline="false"
      ref="formData"
      :model="seachData"
      style="padding:20px"
      size="mini"
      label-width="100px"
    >
      <el-card>

        <el-row style="margin-top: 2px">
          <el-col :span="6">
            <el-form-item label="SKU" prop="sku">
              <el-input
                v-model="seachData.sku"
                clearable
                placeholder=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="英文品名" prop="sku">
              <el-input
                v-model="seachData.declareNameEn"
                clearable
                placeholder=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="中文品名" prop="sku">
              <el-input
                v-model="seachData.declareNameCn"
                clearable
                placeholder=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-button size="mini" type="primary" @click="seach()"
            >搜索
            </el-button>
          </el-col>
          <el-col :span="1">
            <el-button size="mini" type="primary" @click="remark('seachData')"
            >重置
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <el-card class="margin-top">
      <div style="height: 20px;"></div>
      <el-row>
        <el-col :span="3">
          <span>客户名：{{ customerName }}</span>
        </el-col>
        <el-col :span="3">
          <span>运单号：{{ waybillInfo.waybillNo }}</span>
        </el-col>
        <el-col :span="3">
          <span>目的国家：{{ countryName }}</span>
        </el-col>
        <el-col :span="3">
          <span>渠道：{{ channelName }}</span>
        </el-col>
        <el-col :span="3">
          <span>派送地址：{{ waybillInfo.dispatchAddress }}</span>
        </el-col>
        <el-col :span="3">
          <span>件数：{{ waybillInfo.inStockTotalPackages }}CTNS</span>
        </el-col>
        <el-col :span="3">
          <span>重量：{{ waybillInfo.inStockActualWeight }}KG</span>
        </el-col>
        <el-col :span="3">
          <span>体积：{{ waybillInfo.inStockVolume }}CBM</span>
        </el-col>
      </el-row>
      <div style="height: 20px;"></div>
      <el-divider></el-divider>
      <div class="home_input">
        <el-button size="mini" type="primary" style="margin-left: 500px" @click="addDismantle()"
        >确定
        </el-button>
      </div>
      <div style="height: 20px;"></div>
      <el-row>
        <el-col :span="16">
          <div slot="header" class="clearfix relative">
            <span class="title-icon">箱单</span>
          </div>

          <el-table
            ref="moviesTable"
            :data="packData"
            size="mini"
            border
            style="width: 100%"
          >
            <el-table-column
              type="selection"
              :selectable="checkSelectable"
              width="55">
            </el-table-column>
            <el-table-column
              label="序号"
              type="index"
              width="50">
            </el-table-column>
            <el-table-column label="子单号" prop="waybillSubNo">
              <template slot-scope="scope">
              <span :class="{ 'text-red': scope.row.isError }">
                {{ scope.row.waybillSubNo }}
              </span>
              </template>
            </el-table-column>
            <el-table-column label="箱号" prop="startNumNo" width="200px">
              <template slot-scope="scope">
              <span :class="{ 'text-red': scope.row.isError }">
                {{ scope.row.startNumNo }}
              </span>
              </template>
            </el-table-column>
            <el-table-column label="单箱毛重(kg)" prop="weight">
            </el-table-column>
            <el-table-column label="单箱长×宽×高(cm)">
              <template slot-scope="scope">
              <span
              >{{ scope.row.length }} X {{ scope.row.width }} X
                {{ scope.row.height }}</span
              >
              </template>
            </el-table-column>
            <el-table-column label="单箱计费重(kg)" prop="chargedWeight">
            </el-table-column>
            <el-table-column prop="sku" label="SKU" width="200px">
              <template slot-scope="scope">
                <p v-for="pack in scope.row.packSkuList">
                  {{ pack.sku }}
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="declareNameEn" label="英文品名">
              <template slot-scope="scope">
                <p v-for="pack in scope.row.packSkuList">
                  {{ pack.declareNameEn }}
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="declareNameCn" label="中文品名">
              <template slot-scope="scope">
                <p v-for="pack in scope.row.packSkuList">
                  {{ pack.declareNameCn }}
                </p>
              </template>
            </el-table-column>
          </el-table>
          <div style="height: 20px;"></div>
          <el-button size="mini" type="primary" style="margin-left: 500px" @click="saveDismantle()"
          >保存
          </el-button>
        </el-col>
        <el-col :span="1">
          <div class="divider_viv">
            <el-divider direction="vertical" content-position="center"></el-divider>
          </div>
        </el-col>
        <el-col :span="7">
          <el-form :model="dismantleFrom" label-width="150px">
            <el-row v-for="(item, index) in dismantleFrom.items" :key="index">
              <el-row>
                <el-col :span="8">
                </el-col>
                <el-col :span="4">
                  <span style="color: red">{{ item.inStockActualWeight }}KG</span>
                </el-col>
                <el-col :span="4">
                  <span style="color: red">{{ item.inStockVolume }}CBM</span>
                </el-col>
                <el-col :span="4">
                  <span style="color: red">{{ item.inStockTotalPackages }}CTNS</span>
                </el-col>
                <el-col :span="4">
                  <span style="color: red">({{ item.chargedWeight }}KG)</span>
                </el-col>
              </el-row>
              <div style="height: 20px;"></div>
              <el-row>
                <el-col :span="6">
                  <div>
                    <span>{{ item.dismantleNo }}</span>
                  </div>
                  <template v-if="index===dismantleFrom.items.length-1">
                    <el-button type="success" icon="el-icon-edit" size="mini" @click="addDismantle()"
                               circle></el-button>
                  </template>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="checkDelete(index)"
                             circle></el-button>
                </el-col>
                <el-col :span="18">
                  <template v-for="(items, indexs) in item.startNumNos">
                    <el-row>
                      <el-col :span="12">
                        <p>{{ items }}</p>
                      </el-col>
                      <el-col :span="12">
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                                   @click="deleteStartNumNo(index,indexs)" circle></el-button>
                      </el-col>
                    </el-row>
                  </template>
                </el-col>
              </el-row>
              <div style="height: 20px;"></div>
              <el-button type="primary" style="margin-left: 200px" @click="addStartNumNo(index)" plain>加入箱号</el-button>
              <el-divider></el-divider>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <div>
    </div>
  </div>
</template>

<script>
import {ajax} from "@/store/yg/common/utils";
import {clone} from "@/utils/clone";

export default {
  data() {
    return {
      load: false,
      fullscreenLoading: false,
      seachData: {
        waybillId: "",
        sku: "",
        declareNameCn: "",
        declareNameEn: "",
        id: ""
      },
      tableData: {},
      spanArr: [],
      packData: [],
      pos: 0,
      id: this.$route.query.pid,
      dismantleFrom: {
        waybillId: this.$route.query.pid,
        items: []
      },
      waybillInfo: {},
      countryName: "",
      customerName: "",
      channelName: "",
      selectionRow: [],
      allSelectionRow: [],
      fromLength: 0,
      allLength: 0,

    }
  },
  mounted() {
    this.queryWaybillInfo();
    this.querySeaAirDismantle();
    this.seach();
  },
  watch: {
    'allSelectionRow': {
      handler(newUri, oldUri) {
        this.$refs.moviesTable.clearSelection();
      },
    }
  },
  methods: {
    async queryWaybillInfo() {
      const attrs = {
        class: "com.tofba.app.client.seaair.SeaAirExpressListClient"
      };
      this.seachData.id = this.$route.query.pid;
      await ajax("getWaybillInfo", this.seachData, attrs).then(
        res => {
          if (res.code === 200) {
            this.waybillInfo = res.data;
            if (this.waybillInfo.countryId != null) {
              let countryMap = this.$store.state.blank.entry.sources[
                "countrySource"
                ];
              this.countryName = countryMap[this.waybillInfo.countryId];
            }
            if (this.waybillInfo.customerId != null) {
              let customerMap = this.$store.state.blank.entry.sources[
                "customerSource"
                ];
              this.customerName = customerMap[this.waybillInfo.customerId];
            }
            if (this.waybillInfo.inStockChannel != null) {
              let channelNameMap = this.$store.state.blank.entry.sources[
                "channelNameSource"
                ];
              this.channelName = channelNameMap[this.waybillInfo.inStockChannel];
            }

          }
        });
    },
    async querySeaAirDismantle() {
      const attrs = {
        class: "com.tofba.app.client.seaair.SeaAirExpressListClient"
      };
      await ajax("querySeaAirDismantle", this.dismantleFrom, attrs).then(
        res => {
          if (res.code === 200) {
            this.dismantleFrom.items = res.data;
            this.fromLength = this.dismantleFrom.items.length;
            this.allSelectionRow = res.data2;
          }
        });
    },
    async seach() {
      this.fullscreenLoading = true;
      this.seachData.waybillId = this.$route.query.pid;
      const attrs = {
        class: "com.tofba.app.client.seaair.SeaAirExpressListClient"
      };
      ajax("seachPackingList", this.seachData, attrs).then(
        res => {
          if (res.code === 200) {
            if (null != res.data) {
              this.fullscreenLoading = false;
              this.packData = res.data;
              this.allLength = this.packData.length;
            }
          } else {
            this.fullscreenLoading = false;
            this.$message.error(res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    indexMethod(index) {
      return index + 1;
    },
    // clickRow(row) {
    //   this.$refs.moviesTable.toggleRowSelection(row)
    // },
    addDismantle() {
      //判断已经添加的箱号是否满了
      if (this.allSelectionRow.length === this.allLength || this.allSelectionRow.length > this.allLength) {
        this.$message.error("已无箱号可分配");
        return;
      }
      let dismantleWaybill = {};
      // this.dismantleFrom.items.push(singleWaybill);
      //获取选中的数据
      this.selectionRow = this.$refs.moviesTable.selection;
      //获取最末尾的字母
      var option='';
      if(this.dismantleFrom.items.length>0){
        var disNo= this.dismantleFrom.items[this.dismantleFrom.items.length-1].dismantleNo;
        disNo=disNo.substr(disNo.length-1);
        option=String.fromCharCode(disNo.charCodeAt(0)+1);
      }else{
        option=String.fromCharCode('A'.charCodeAt(0));
      }
      // var option = String.fromCharCode('A'.charCodeAt(0) + this.fromLength);
      // var option = String.fromCharCode(disNo.charCodeAt(0) + this.fromLength);
      var dismantleNo = this.waybillInfo.waybillNo + option;
      let inStockActualWeight = null;
      let inStockVolume = null;
      let chargedWeight = null;
      let volumeWeight = null;
      let startNumNos = [];
      for (var i = 0; i < this.selectionRow.length; i++) {
        inStockActualWeight += this.selectionRow[i].weight;
        inStockVolume += this.selectionRow[i].totalVolumn;
        chargedWeight += this.selectionRow[i].chargedWeight;
        volumeWeight += this.selectionRow[i].volumeWeight;
        startNumNos.push(this.selectionRow[i].startNumNo);
        this.allSelectionRow.push(this.selectionRow[i]);
      }
      dismantleWaybill["dismantleNo"] = dismantleNo;
      if (this.selectionRow.length > 0) {
        dismantleWaybill["inStockTotalPackages"] = this.selectionRow.length;
      }else{
        dismantleWaybill["inStockTotalPackages"]=0;
      }
      if (inStockActualWeight != null) {
        dismantleWaybill["inStockActualWeight"] = inStockActualWeight.toFixed(2);
      }else{
        dismantleWaybill["inStockActualWeight"]=0;
      }
      if (inStockVolume != null) {
        dismantleWaybill["inStockVolume"] = inStockVolume.toFixed(2);
      }else{
        dismantleWaybill["inStockVolume"] =0;
      }
      if (chargedWeight != null) {
        dismantleWaybill["chargedWeight"] = chargedWeight.toFixed(2);
      }else{
        dismantleWaybill["chargedWeight"] =0;
      }
      if (volumeWeight != null) {
        dismantleWaybill["volumeWeight"] = volumeWeight.toFixed(2);
      }else{
        dismantleWaybill["volumeWeight"] =0;
      }
      dismantleWaybill["startNumNos"] = startNumNos;
      this.dismantleFrom.items.push(dismantleWaybill);
      this.fromLength++;
    },
    saveDismantle() {
      // if (this.dismantleFrom.items.length === 0) {
      //   this.$message.error("拆单数据不存在");
      //   return;
      // }
      this.fullscreenLoading = true;
      const attrs = {
        class: "com.tofba.app.client.seaair.SeaAirExpressListClient"
      };
      ajax("saveSeaAirDismantle", this.dismantleFrom, attrs).then(
        res => {
          if (res.code === 200) {
            this.fullscreenLoading = false;
            location.reload();
          } else {
            this.fullscreenLoading = false;
            location.reload();
          }
        });
    },
    checkSelectable(row) {
      if (this.allSelectionRow.length > 0) {
        if (this.allSelectionRow.some(item => item.startNumNo === row.startNumNo)) {
          return false
        } else {
          return true;
        }
      } else {
        return true;
      }
    },
    checkDelete(index){
      this.$confirm("确定移除当前运单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteDismantle(index);
        }).catch(() => {});
    },
    async deleteDismantle(index) {
          console.log(this.dismantleFrom.items[index]);
          var id = this.dismantleFrom.items[index].id;
          if (id != null) {
            const attrs = {
              class: "com.tofba.app.client.seaair.SeaAirExpressListClient"
            };
            this.seachData.id = id;
            let res = await ajax("querySeaAirWaybill", this.seachData, attrs);
            if (res.code === 200) {
              if (null != res.data) {
                if (res.data.status > 40) {
                  this.$message.error("该拆单号已出库，无法进行更改/删除操作");
                  return;
                }
              }
            } else {
              this.$message.error("系统异常");
              return;
            }
          }
          let startNumNos = [];
          startNumNos = this.dismantleFrom.items[index].startNumNos;
          if (startNumNos != null && startNumNos.length > 0) {
            for (var i = 0; i < startNumNos.length; i++) {
              for (var j = 0; j < this.allSelectionRow.length; j++) {
                if (startNumNos[i] === this.allSelectionRow[j].startNumNo) {
                  this.allSelectionRow.splice(j, 1);
                }
              }
            }
          }
          this.dismantleFrom.items.splice(index, 1);
          if(this.fromLength>0){
            this.fromLength=this.fromLength-1;
          }
    },
    async deleteStartNumNo(index, indexs) {
      var id = this.dismantleFrom.items[index].id;
      if (id != null) {
        const attrs = {
          class: "com.tofba.app.client.seaair.SeaAirExpressListClient"
        };
        this.seachData.id = id;
        let res = await ajax("querySeaAirWaybill", this.seachData, attrs);
        if (res.code === 200) {
          if (null != res.data) {
            if (res.data.status > 40) {
              this.$message.error("该拆单号已出库，无法进行更改/删除操作");
              return;
            }
          }
        } else {
          this.$message.error("系统异常");
          return;
        }
      }
      let startNumNo = null;
      startNumNo = this.dismantleFrom.items[index].startNumNos[indexs];
      for (var j = 0; j < this.allSelectionRow.length; j++) {
        if (startNumNo === this.allSelectionRow[j].startNumNo) {
          this.dismantleFrom.items[index].inStockActualWeight = (this.dismantleFrom.items[index].inStockActualWeight - this.allSelectionRow[j].weight).toFixed(2);
          this.dismantleFrom.items[index].inStockVolume = (this.dismantleFrom.items[index].inStockVolume - this.allSelectionRow[j].totalVolumn).toFixed(2);
          this.dismantleFrom.items[index].chargedWeight = (this.dismantleFrom.items[index].chargedWeight - this.allSelectionRow[j].chargedWeight).toFixed(2);
          this.dismantleFrom.items[index].volumeWeight = (this.dismantleFrom.items[index].volumeWeight - this.allSelectionRow[j].volumeWeight).toFixed(2);
          this.dismantleFrom.items[index].inStockTotalPackages = this.dismantleFrom.items[index].inStockTotalPackages - 1;
          this.allSelectionRow.splice(j, 1);
        }
      }
      this.dismantleFrom.items[index].startNumNos.splice(indexs, 1);
    },
    addStartNumNo(index) {
      this.selectionRow = this.$refs.moviesTable.selection;
      if (this.selectionRow.length > 0) {
        let inStockActualWeight = 0;
        let inStockVolume = 0;
        let chargedWeight = 0;
        let volumeWeight = 0;
        for (var i = 0; i < this.selectionRow.length; i++) {
          this.dismantleFrom.items[index].startNumNos.push(this.selectionRow[i].startNumNo);
          this.allSelectionRow.push(this.selectionRow[i]);
          inStockActualWeight += this.selectionRow[i].weight;
          inStockVolume += this.selectionRow[i].totalVolumn;
          chargedWeight += this.selectionRow[i].chargedWeight;
          volumeWeight += this.selectionRow[i].volumeWeight;
        }
        console.log(this.dismantleFrom.items[index]);
        if (inStockActualWeight != null) {
          this.dismantleFrom.items[index].inStockActualWeight = (parseFloat(this.dismantleFrom.items[index].inStockActualWeight) + parseFloat(inStockActualWeight)).toFixed(2);
          console.log(this.dismantleFrom.items[index].inStockActualWeight)
        }
        if (inStockVolume != null) {
          this.dismantleFrom.items[index].inStockVolume = (parseFloat(this.dismantleFrom.items[index].inStockVolume) + parseFloat(inStockVolume)).toFixed(2);
        }
        if (chargedWeight != null) {
          this.dismantleFrom.items[index].chargedWeight = (parseFloat(this.dismantleFrom.items[index].chargedWeight) + parseFloat(chargedWeight)).toFixed(2);
        }
        if (volumeWeight != null) {
          this.dismantleFrom.items[index].volumeWeight = (parseFloat(this.dismantleFrom.items[index].volumeWeight) + parseFloat(chargedWeight)).toFixed(2);
        }
        this.dismantleFrom.items[index].inStockTotalPackages = this.dismantleFrom.items[index].inStockTotalPackages + this.selectionRow.length;

      } else {
        this.$message.error("请选择要添加的数据");
        return;
      }
    },
    remark(val) {
      this.seachData = {};
    }
  }
}
</script>

<style scoped>
.divider_viv >>> .el-divider--vertical {
  height: 600px;
  vertical-align: text-top;
}
</style>
